<template>
  <div class="login-container" @click="handleBackgroundClick">
    <!-- 装饰性背景元素 -->
    <div class="background-decorations">
      <div class="bg-circle bg-circle-1"></div>
      <div class="bg-circle bg-circle-2"></div>
      <div class="bg-circle bg-circle-3"></div>
    </div>
    
    <!-- 主要内容容器 -->
    <div class="login-content-wrapper" @click.stop>
      <!-- 头像区域 - 居中显示 -->
    <div class="avatar-section">
      <!-- 大字体时间显示 -->
      <div class="large-time-display">
        <div class="time-digits">{{ formattedTime }}</div>
        <div class="date-info">{{ formattedDate }} · {{ lunarDate }}</div>
      </div>
        
        <div 
          class="user-avatar" 
          @click="toggleLoginForm" 
          :class="{ 'avatar-clicked': showLoginForm }"
          @mousemove="handleAvatarMouseMove"
          @mouseleave="handleAvatarMouseLeave"
          :style="avatarStyle"
        >
          <img :src="userAvatar" alt="用户头像" class="avatar-image" />
        </div>
        <h2 class="username-display">{{ displayName }}</h2>
        <p class="login-hint-text" v-if="!showLoginForm">点击头像登录</p>
      </div>
      
      <!-- 登录表单 - 初始隐藏，点击头像后显示 -->
      <transition name="form-fade">
        <div v-if="showLoginForm" class="form-section">
          <el-form ref="loginForm" :model="formData" :rules="rules" class="apple-login-form" @keyup.enter="handleEnterKey">
            <!-- 用户名输入框 - 始终显示 -->
            <transition name="input-fade">
              <el-form-item class="apple-form-item">
                <el-input 
                  v-model="formData.username" 
                  placeholder="用户名" 
                  class="apple-input" 
                  auto-complete="username"
                  @input="handleUsernameInput"
                />
              </el-form-item>
            </transition>
            
            <!-- 密码输入框 - 用户名不为空时显示 -->
            <transition name="input-fade">
              <el-form-item v-if="showPasswordInput" class="apple-form-item">
                <el-input 
                  v-model="formData.password" 
                  type="password" 
                  placeholder="密码" 
                  class="apple-input"
                  auto-complete="current-password"
                  show-password
                  @input="handlePasswordInput"
                />
              </el-form-item>
            </transition>
            
            <!-- 登录按钮和忘记密码按钮 -->
            <transition name="input-fade">
              <div v-if="showLoginButton || !showPasswordInput">
                <el-form-item v-if="showLoginButton">
                  <el-button 
                    type="primary" 
                    class="apple-login-button" 
                    @click="handleLogin"
                    :loading="loading"
                    :disabled="loading"
                  >
                    登录
                  </el-button>
                </el-form-item>
                
                <el-form-item class="forgot-password-container">
                  <el-button 
                    type="text" 
                    class="forgot-password-button"
                    @click="showDefaultCredentials"
                  >
                    忘记密码？
                  </el-button>
                </el-form-item>
              </div>
            </transition>
          </el-form>
          
          <!-- <transition name="input-fade">
            <div v-if="showLoginForm" class="login-hint">
              <p>默认账号: <span class="hint-text">yuwen</span></p>
              <p>默认密码: <span class="hint-text">Passw0rd</span></p>
            </div>
          </transition> -->
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { Solar } from 'lunar-javascript';
import notificationService from '../utils/notificationService.js';
import authAPI from '../api/auth.js';
const router = useRouter();
const loading = ref(false);
const showLoginForm = ref(false); // 控制登录表单显示状态
const showPasswordInput = ref(false); // 控制密码输入框显示状态
const showLoginButton = ref(false); // 控制登录按钮显示状态
const avatarStyle = reactive({ transform: 'translate(0, 0)' }); // 头像位置样式
const formData = reactive({
  username: '',
  password: ''
});

// 日期和时间显示相关
const formattedDate = ref('');
const formattedTime = ref('');
const lunarDate = ref('');
let timeUpdateTimer = null;

// 计算农历日期函数
  const calculateLunarDate = () => {
    try {
      const now = new Date();
      // 创建Solar对象并转换为农历
      const solar = Solar.fromDate(now);
      const lunar = solar.getLunar();
      
      // 获取农历年份（干支纪年）、月份和日期
      const lunarYear = lunar.getYearInGanZhi(); // 获取干支纪年，如辛亥年
      const lunarMonth = lunar.getMonthInChinese(); // 获取包含闰月信息的中文月份
      const lunarDay = lunar.getDayInChinese(); // 获取中文数字表示的日期
      
      // 组合完整的农历日期字符串
      lunarDate.value = lunarYear + lunarMonth + lunarDay;
    } catch (error) {
      console.error('农历计算错误:', error);
      lunarDate.value = '农历日期';
    }
  };

  // 更新日期和时间
  const updateDateTime = () => {
    const now = new Date();
    
    // 格式化日期：年-月-日 星期几
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const weekday = weekdays[now.getDay()];
    formattedDate.value = `${year}年${month}月${day}日 ${weekday}`;
    
    // 格式化时间：时:分:秒
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    formattedTime.value = `${hours}:${minutes}:${seconds}`;
    
    // 调用农历日期计算函数
    calculateLunarDate();
  };

  // 初始化时间和启动定时器
onMounted(() => {
  updateDateTime(); // 立即更新一次
  timeUpdateTimer = setInterval(updateDateTime, 1000); // 每秒更新一次
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timeUpdateTimer) {
    clearInterval(timeUpdateTimer);
  }
});

  // 处理鼠标移动事件，实现头像吸附效果
const handleAvatarMouseMove = (event) => {
  if (showLoginForm.value) return; // 登录表单显示时禁用吸附效果
  
  // 获取头像元素
  const avatar = event.currentTarget;
  const rect = avatar.getBoundingClientRect();
  
  // 计算鼠标相对于头像中心的位置
  const centerX = rect.left + rect.width / 2;
  const centerY = rect.top + rect.height / 2;
  const mouseX = event.clientX;
  const mouseY = event.clientY;
  
  // 计算鼠标与头像中心的偏移量
  const deltaX = mouseX - centerX;
  const deltaY = mouseY - centerY;
  
  // 设置最大偏移量，让头像跟随鼠标但不会移动太多
  const maxOffset = 20;
  
  // 计算头像应该移动的距离（吸附强度）
  const moveX = Math.max(Math.min(deltaX * 0.15, maxOffset), -maxOffset);
  const moveY = Math.max(Math.min(deltaY * 0.15, maxOffset), -maxOffset);
  
  // 更新头像位置
  avatarStyle.transform = `translate(${moveX}px, ${moveY}px) scale(1.05)`;
};

// 处理鼠标离开事件，让头像回到原位
const handleAvatarMouseLeave = () => {
  if (showLoginForm.value) return; // 登录表单显示时禁用吸附效果
  
  // 平滑地将头像重置到初始位置
  avatarStyle.transform = 'translate(0, 0) scale(1)';
};

// 点击背景时隐藏登录表单
const handleBackgroundClick = () => {
  if (showLoginForm.value) {
    showLoginForm.value = false;
    // 重置所有状态和表单
    setTimeout(() => {
      formData.username = '';
      formData.password = '';
      showPasswordInput.value = false;
      showLoginButton.value = false;
    }, 300); // 等待动画完成后重置
  }
};

// 注入用户状态管理
const userStore = inject('userStore');

// 默认头像路径
const userAvatar = 'http://14.103.171.191:8080/images/640-8.svg';
// 显示名称
const displayName = '设备管理系统';

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

// 切换登录表单显示状态
const toggleLoginForm = () => {
  showLoginForm.value = !showLoginForm.value;
  
  // 重置状态
  if (!showLoginForm.value) {
    showPasswordInput.value = false;
    showLoginButton.value = false;
    formData.username = '';
    formData.password = '';
    return;
  }
  
  // 当表单显示时，聚焦到用户名输入框
  setTimeout(() => {
    const usernameInput = document.querySelector('.apple-input input');
    if (usernameInput) {
      usernameInput.focus();
    }
  }, 300);
};

// 处理用户名输入
const handleUsernameInput = () => {
  if (formData.username.trim() && !showPasswordInput.value) {
    // 用户名不为空且密码输入框未显示时，延迟显示密码输入框以获得动画效果
    setTimeout(() => {
      showPasswordInput.value = true;
      // 聚焦到密码输入框
      setTimeout(() => {
        const passwordInputs = document.querySelectorAll('.apple-input input');
        if (passwordInputs.length > 1) {
          passwordInputs[1].focus();
        }
      }, 150);
    }, 300);
  } else if (!formData.username.trim()) {
    // 用户名清空时，隐藏密码输入框和登录按钮
    showPasswordInput.value = false;
    showLoginButton.value = false;
    formData.password = '';
  }
};

// 处理密码输入
const handlePasswordInput = () => {
  if (formData.password.trim() && !showLoginButton.value) {
    // 密码不为空且登录按钮未显示时，延迟显示登录按钮以获得动画效果
    setTimeout(() => {
      showLoginButton.value = true;
    }, 300);
  } else if (!formData.password.trim()) {
    // 密码清空时，隐藏登录按钮
    showLoginButton.value = false;
  }
};

// 显示默认账号和密码
const showDefaultCredentials = () => {
  // 自动填充默认用户名和密码
  formData.username = 'yuwen';
  formData.password = 'Passw0rd';
  
  // 确保密码输入框和登录按钮都显示出来
  showPasswordInput.value = true;
  showLoginButton.value = true;
  
  // 显示提示信息
  notificationService.success('已自动填充默认账号和密码');
};

// 处理回车键
const handleEnterKey = () => {
  if (formData.username && !formData.password) {
    // 如果只输入了用户名，聚焦到密码输入框
    showPasswordInput.value = true;
    setTimeout(() => {
      const passwordInputs = document.querySelectorAll('.apple-input input');
      if (passwordInputs.length > 1) {
        passwordInputs[1].focus();
      }
    }, 150);
  } else if (formData.username && formData.password) {
    // 如果用户名和密码都已输入，执行登录
    handleLogin();
  }
};

const handleLogin = async () => {
  // 简单的表单验证
  if (!formData.username || !formData.password) {
    notificationService.warning('请填写用户名和密码');
    return;
  }
  
  loading.value = true;
  
  try {
    // 调用登录API
    const response = await authAPI.login({
      username: formData.username,
      password: formData.password
    });
    
    // 检查响应是否成功
    // 支持20000-20003成功状态码范围
      if ((response.code >= 20000 && response.code <= 20003) && response.data) {
      const userData = response.data;
      // 保存accessToken和refreshToken到localStorage
      localStorage.setItem('accessToken', userData.accessToken);
      localStorage.setItem('refreshToken', userData.refreshToken);
      
      // 保存用户完整信息到localStorage
      localStorage.setItem('userInfo', JSON.stringify({
        userId: userData.userId,
        username: userData.userName,
        nickName: userData.nickName,
        realName: userData.realName,
        avatar: userData.avatar,
        phone: userData.phone,
        email: userData.email,
        deptId: userData.deptId,
        postId: userData.postId,
        status: userData.status,
        accessTokenExpire: userData.accessTokenExpire
      }));
      
      // 使用全局状态管理更新用户信息
      userStore.updateUserInfo({ 
        userId: userData.userId,
        username: userData.userName,
        nickName: userData.nickName,
        realName: userData.realName,
        // 直接使用后端返回的头像地址，确保获取正确的avatar字段
        avatar: userData.avatar,
        phone: userData.phone,
        email: userData.email,
        role: '管理员', // 可以根据实际返回的角色信息设置
        accessTokenExpire: userData.accessTokenExpire
      });
    
      notificationService.success(response.message || '登录成功');
      
      // 跳转到首页
      router.push('/');
    } else {
      notificationService.error(response.message || '操作失败');
    }
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '登录失败，请重试'
    notificationService.error(errorMessage)
    console.error('登录请求错误:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  overflow: hidden;
}

/* 背景样式 */
/* 背景样式 */
.login-container {
  min-height: 100vh;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  overflow: hidden;
}

/* 装饰性背景元素 */
.background-decorations {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.15);
  animation: float 8s ease-in-out infinite;
}

.bg-circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  right: -100px;
  animation-delay: 0s;
}

.bg-circle-2 {
  width: 200px;
  height: 200px;
  bottom: -50px;
  left: -50px;
  animation-delay: 2s;
}

.bg-circle-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  left: 10%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(5deg);
  }
}

/* 主要内容容器 - 垂直布局 */
.login-content-wrapper {
  width: 100%;
  max-width: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 1;
  min-height: 60vh;
  justify-content: flex-start;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 10vh;
  margin-bottom: 20px;
  position: relative;
  z-index: 5;
}

.large-time-display {
    margin-bottom: 40px;
    margin-top: -20px;
    text-align: center;
    z-index: 10;
    position: relative;
    padding: 10px;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    min-width: 300px;
    width: 300px;
  }
  
  .time-digits {
    font-size: 70px;
    font-weight: 200;
    color: white;
    letter-spacing: 2px;
    text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    margin-bottom: 8px;
    font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
    opacity: 1;
  }

.date-info {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  letter-spacing: 0.5px;
  text-shadow: 0 1px 5px rgba(0, 0, 0, 0.3);
  opacity: 1;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .time-digits {
    font-size: 36px;
  }
  
  .date-info {
    font-size: 13px;
  }
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  margin-bottom: 20px;
  background: white;
  cursor: pointer;
  transition: transform 0.4s cubic-bezier(0.2, 0.85, 0.4, 1.275), border-color 0.3s ease, box-shadow 0.3s ease;
  position: relative;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
}

.user-avatar.avatar-clicked {
  transform: scale(1.1);
  border-color: #007aff;
  box-shadow: 0 0 20px rgba(0, 122, 255, 0.5);
}

.user-avatar::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 140px;
  height: 140px;
  border-radius: 50%;
  border: 2px solid rgba(255, 255, 255, 0.3);
  opacity: 0;
  transition: all 0.3s ease;
}

.user-avatar:hover::after {
  opacity: 1;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 0;
  }
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.user-avatar:hover .avatar-image {
  transform: scale(1.05);
}

.username-display {
  color: white;
  font-size: 24px;
  font-weight: 500;
  margin: 0;
  text-align: center;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.date-time-display {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
  margin: 8px 0;
  font-weight: 400;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.login-hint-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  margin: 10px 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  animation: fadeInOut 2s infinite;
}

@keyframes fadeInOut {
  0%, 100% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
}

/* 表单区域 - 初始隐藏，点击头像后显示 */
.form-section {
  width: 100%;
  margin-bottom: 20px;
}

.apple-login-form {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.apple-form-item {
  margin-bottom: 16px;
  overflow: hidden;
}

.apple-input {
  height: 44px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.apple-input:focus-within {
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
}

.apple-login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  background: #007aff;
  border: none;
  transition: all 0.3s ease;
}

.forgot-password-button {
  color: #007aff;
  font-size: 13px;
  padding: 0 !important;
  margin: 0 !important;
  min-width: auto;
  height: auto;
  line-height: normal;
  transition: color 0.3s ease;
}

.forgot-password-button:hover {
  color: #0051d5;
  background-color: transparent;
}

/* 减小忘记密码按钮所在表单项的内边距 */
.forgot-password-container {
  margin: 0 !important;
  padding: 4px 0 !important;
  height: auto;
  line-height: normal;
}

.apple-login-button:hover {
  background: #0051d5;
  transform: translateY(-1px);
}

.login-hint {
  text-align: center;
  margin-top: 20px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.login-hint p {
  margin: 5px 0;
}

.hint-text {
  color: white;
  font-weight: 500;
  padding: 2px 6px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

/* 表单显示/隐藏的动画效果 */
.form-fade-enter-active,
.form-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: top center;
  overflow: hidden;
}

.form-fade-enter-from {
  opacity: 0;
  transform: translateY(-10px) scale(0.98);
  max-height: 0;
}

.form-fade-enter-to {
  opacity: 1;
  transform: translateY(0) scale(1);
  max-height: 400px;
}

.form-fade-leave-from {
  opacity: 1;
  transform: translateY(0) scale(1);
  max-height: 400px;
}

.form-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.98);
  max-height: 0;
}

.form-fade-enter-to,
.form-fade-leave-from {
  opacity: 1;
  transform: translateY(0) scale(1);
  max-height: 400px;
}

/* 输入框和按钮的显示/隐藏动画 */
.input-fade-enter-active,
.input-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  max-height: 60px;
}

.input-fade-enter-from {
  opacity: 0;
  transform: translateY(10px);
  max-height: 0;
  margin-bottom: 0;
}

.input-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
  margin-bottom: 0;
}

.input-fade-enter-to,
.input-fade-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 60px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-content-wrapper {
    min-height: 70vh;
  }
  
  .user-avatar {
    width: 100px;
    height: 100px;
  }
  
  .username-display {
    font-size: 20px;
  }
  
  .login-hint-text {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .avatar-section {
    margin-top: 5vh;
  }
  
  .user-avatar {
    width: 80px;
    height: 80px;
  }
  
  .username-display {
    font-size: 18px;
  }
  
  .apple-login-form {
    padding: 16px;
  }
}
</style>